package com.warehouse_management.login.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.deploy.net.HttpResponse;
import com.warehouse_management.login.model.Users;
import com.warehouse_management.login.service.LoginService;
import com.warehouse_management.util.VerifyUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * @PACKAGE_NAME: com.warehouse_management.login.controller
 * @NAME: LoginController
 * @USER: ZhouYongCheng
 * @DATE: 2022/10/5
 * @TIME: 12:30
 * @Description: 登录控制层
 */
@Controller
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/login/{uname}/{pwd}/{yzm}")
    @ResponseBody
    public String User_Login(@PathVariable("uname") String uname,
                             @PathVariable("pwd") String pwd,
                             @PathVariable("yzm") String yzm,HttpSession session){
        String verifyCode1 = (String) session.getAttribute("verifyCode");
        if (verifyCode1.equalsIgnoreCase(yzm)){
            QueryWrapper<Users> qw = new QueryWrapper<>();
            qw.eq("uname",uname).eq("upassword",pwd);

            Users user = loginService.getOne(qw);

            if (user == null){
                return JSON.toJSONString("two");
            }else {
                session.setAttribute("loginUser",user);
                return JSON.toJSONString("one");
            }
        }

        return JSON.toJSONString("three");
    }

    @RequestMapping("/toVerifyPic")
    public void toVerifyPic(HttpSession session, HttpServletResponse response){
        Map<String, Object> data = VerifyUtil.generateVerify();
        //获取验证码
        String verifyCode = (String) data.get("verifyCode");
        //将验证码存入session
        session.setAttribute("verifyCode", verifyCode);
        //获取图片
        BufferedImage verifyPic = (BufferedImage) data.get("verifyPic");
        //输出图片给前端，使用工具类ImageIO
        try {
            ImageIO.write(verifyPic, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
